package com.dkx.springbootwebsocket.controller;

import com.dkx.springbootwebsocket.service.WebSocketMessageService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 杜科璇
 * @Description: TODO
 * @Date: 2025/10/31 18:45
 * @Version: 1.0
 */

// MessageController.java
@RestController
@RequestMapping("/api/message")
@Slf4j
public class MessageController {

    @Autowired
    private WebSocketMessageService messageService;

//    @Autowired
//    private RedisTemplate<String, Object> redisTemplate;
//    /**
//     * 调试接口：检查离线消息状态
//     */
//    @GetMapping("/debug/offline-status/{userId}")
//    public ResponseEntity<?> checkOfflineMessageStatus(@PathVariable String userId) {
//        try {
//            Map<String, Object> result = new HashMap<>();
//
//            String key = "offline:msg:" + userId;
//            Long size = redisTemplate.opsForList().size(key);
//
//            result.put("userId", userId);
//            result.put("offlineMessageCount", size != null ? size : 0);
//            result.put("hasOfflineMessages", size != null && size > 0);
//
//            // 检查用户在线状态
//            boolean isOnline = messageService.isUserOnline(userId);
//            result.put("userOnline", isOnline);
//
//            // 检查用户订阅
//            Map<String, Object> subscriptionStatus = messageService.debugCheckUserSubscriptions(userId);
//            result.put("subscriptionStatus", subscriptionStatus);
//
//            return ResponseEntity.ok(result);
//        } catch (Exception e) {
//            log.error("检查离线消息状态失败", e);
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("检查离线消息状态失败");
//        }
//    }


    /**
     * 发送点对点消息
     */
    @PostMapping("/sendToUser")
    public ResponseEntity<?> sendToUser(@RequestBody SendMessageRequest request) {
        try {
            messageService.sendToUser(request.getFromUser(), request.getToUser(), request.getContent());
            return ResponseEntity.ok("消息发送成功");
        } catch (Exception e) {
            log.error("发送点对点消息失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("消息发送失败");
        }
    }

    /**
     * 发送群组消息
     */
    @PostMapping("/sendToGroup")
    public ResponseEntity<?> sendToGroup(@RequestBody SendGroupMessageRequest request) {
        try {
            messageService.sendToGroup(request.getFromUser(), request.getToUsers(), request.getContent());
            return ResponseEntity.ok("群组消息发送成功");
        } catch (Exception e) {
            log.error("发送群组消息失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("群组消息发送失败");
        }
    }

    /**
     * 发送广播消息
     */
    @PostMapping("/broadcast")
    public ResponseEntity<?> broadcast(@RequestBody SendMessageRequest request) {
        try {
            messageService.sendToAll(request.getFromUser(), request.getContent());
            return ResponseEntity.ok("广播消息发送成功");
        } catch (Exception e) {
            log.error("发送广播消息失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("广播消息发送失败");
        }
    }

    /**
     * 获取在线用户列表
     */
    @GetMapping("/onlineUsers")
    public ResponseEntity<List<String>> getOnlineUsers() {
        // 这里简化实现，实际项目中应该维护一个在线用户列表
        // 或者从Redis中获取所有在线的用户
        List<String> onlineUsers = new ArrayList<>();
        // 示例：检查一些常见用户是否在线
        String[] testUsers = {"1", "2", "3", "4"};
        for (String user : testUsers) {
            if (messageService.isUserOnline(user)) {
                onlineUsers.add(user);
            }
        }
        return ResponseEntity.ok(onlineUsers);
    }

    /**
     * 检查特定用户是否在线
     */
    @GetMapping("/online/{userId}")
    public ResponseEntity<Map<String, Object>> isUserOnline(@PathVariable String userId) {
        boolean isOnline = messageService.isUserOnline(userId);
        Map<String, Object> response = new HashMap<>();
        response.put("userId", userId);
        response.put("online", isOnline);
        response.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(response);
    }

//    /**
//     * 调试接口：直接发送测试消息
//     */
//    @PostMapping("/debug/send-direct")
//    public ResponseEntity<?> sendDirectMessage(@RequestBody SendMessageRequest request) {
//        try {
//            log.info("调试接口：直接发送消息 from={}, to={}, content={}",
//                    request.getFromUser(), request.getToUser(), request.getContent());
//
//            // 直接使用 messagingTemplate 发送
//            messageService.debugSendDirectMessage(request.getFromUser(), request.getToUser(), request.getContent());
//
//            return ResponseEntity.ok("调试消息发送完成");
//        } catch (Exception e) {
//            log.error("调试消息发送失败", e);
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("调试消息发送失败");
//        }
//    }
//
//    /**
//     * 调试接口：检查用户订阅状态
//     */
//    @GetMapping("/debug/subscriptions/{userId}")
//    public ResponseEntity<?> checkUserSubscriptions(@PathVariable String userId) {
//        try {
//            Map<String, Object> result = messageService.debugCheckUserSubscriptions(userId);
//            return ResponseEntity.ok(result);
//        } catch (Exception e) {
//            log.error("检查用户订阅失败", e);
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("检查用户订阅失败");
//        }
//    }
}

@Data
class SendMessageRequest {
    private String fromUser;
    private String toUser;
    private String content;
}

@Data
class SendGroupMessageRequest {
    private String fromUser;
    private List<String> toUsers;
    private String content;
}